import { Button, Card, Col, Input, message, Pagination, Row, Table, type TableProps, Tag } from 'antd'
import React, { useEffect, useState } from 'react'
import { getContractList } from '../../api/contract.ts'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { setData, setFormData, setPageNumber, setPageSize, setTotal } from '../../store/finance/contractSlice.ts'

export interface SearchType {
  contractNo: string
  person: string
  tel: string
  pageNumber?: number
  pageSize?: number
}

interface DataType {
  id: string
  contractNo: string
  type: string
  name: string
  startDate: string
  endDate: string
  jia: string
  yi: string
  status: string
}

export default function Contract() {
  const { data, pageSize, total, pageNumber } = useSelector((state: any) => state.contractSlice)
  const [loading, setLoading] = useState<boolean>(false)
  const [searchParams] = useSearchParams()
  const dispatch = useDispatch()
  const navigate = useNavigate()

  const [queryParams, setQueryParams] = useState<SearchType>({
    contractNo: '',
    person: '',
    tel: '',
  })

  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'No.',
      key: 'index',
      render(_value: number, _record: DataType, index: number) {
        return index + 1
      },
    },
    {
      title: '合同编号',
      dataIndex: 'contractNo',
      key: 'contractNo',
    },
    {
      title: '合同类别',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '合同名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '合同开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
    },
    {
      title: '合同结束如期',
      dataIndex: 'endDate',
      key: 'endDate',
    },
    {
      title: '甲方',
      dataIndex: 'jia',
      key: 'jia',
    },
    {
      title: '乙方',
      dataIndex: 'yi',
      key: 'yi',
    },
    {
      title: '操作',
      key: 'operate',
      render(_value: number, record: DataType) {
        function handleNavToDetail() {
          dispatch(setFormData(record))
          navigate('/finance/surrender?fromContract=true')
        }

        return (
          <Button type="primary" size="small" onClick={handleNavToDetail}>
            合同详情
          </Button>
        )
      },
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      render(value: number) {
        if (value == 1) {
          return <Tag>未审批</Tag>
        } else if (value == 2) {
          return <Tag color="green">审批通过</Tag>
        } else {
          return <Tag color="red">审批拒绝</Tag>
        }
      },
    },
  ]

  const loadData = async (pageNumber: number, pageSize: number) => {
    console.log(pageNumber, pageSize)
    setLoading(true)
    await getContractList({ ...queryParams, pageNumber, pageSize })
      .then(({ data: { list, total } }) => {
        dispatch(setData(list))
        dispatch(setTotal(total))
      })
      .catch((err) => {
        message.error(err.message || String(err))
      })
      .finally(() => {
        setLoading(false)
      })
  }

  useEffect(() => {
    const isReturn: string | null = searchParams.get('fromDetail')
    if (!isReturn || data.length <= 0) {
      loadData(pageNumber, pageSize)
    }
  }, [pageNumber, pageSize])

  const handleChangePage = (pageNumber: number, pageSize: number) => {
    dispatch(setPageNumber(pageNumber))
    dispatch(setPageSize(pageSize))
    loadData(pageNumber, pageSize)
  }

  function handleRest() {
    setQueryParams({
      contractNo: '',
      person: '',
      tel: '',
    })
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setQueryParams({
      ...queryParams,
      [name]: value,
    })
  }

  return (
    <div>
      <Card>
        <Row gutter={16} className="search">
          <Col span={7}>
            <p>合同编号:</p>
            <Input name="contractNo" value={queryParams.contractNo} onChange={handleInputChange}></Input>
          </Col>
          <Col span={7}>
            <p>联系人:</p>
            <Input name="person" value={queryParams.person} onChange={handleInputChange}></Input>
          </Col>
          <Col span={7}>
            <p>联系电话:</p>
            <Input name="tel" value={queryParams.tel} onChange={handleInputChange}></Input>
          </Col>
          <Col span={3}>
            <Button type="primary" onClick={() => loadData(pageNumber, pageSize)}>
              查询
            </Button>
            <Button className="ml" onClick={handleRest}>
              重置
            </Button>
          </Col>
        </Row>
      </Card>
      <Card>
        <Table columns={columns} loading={loading} dataSource={data} rowKey="id" pagination={false} />
        <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={total}
          pageSize={pageSize}
          className="fr"
          onChange={handleChangePage}
          current={pageNumber}
        />
      </Card>
    </div>
  )
}
